<template>
  <div class="main">
    <div v-show="false">总价格：{{ allPrice }}</div>
    <div class="air-column">
      <h2>乘机人</h2>
      <el-form
        class="member-info"
        :model="item"
        :rules="rules"
        ref="ruleForm2"
        v-for="(item, index) in users"
        :key="index"
      >
        <div class="member-info-item">
          <el-form-item label="乘机人类型" prop="username">
            <el-input
              placeholder="姓名"
              class="input-with-select"
              v-model="item.username"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item label="证件类型" prop="id">
            <el-input
              placeholder="证件号码"
              class="input-with-select"
              v-model="item.id"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers"
        >添加乘机人</el-button
      >
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <el-checkbox-group v-model="insurances">
          <div
            class="insurance-item"
            v-for="(item, index) in ticketdata.insurances"
            :key="index"
          >
            <el-checkbox :label="item.id" border
              >{{ item.type }}：￥{{ item.price }}/份×{{
                users.length
              }}
              最高赔付{{ item.compensation }}</el-checkbox
            >
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="80px"
          :model="ruleForm"
          :rules="rules"
          ref="ruleform"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="ruleForm.contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input placeholder="请输入内容" v-model="ruleForm.contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="ruleForm.captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="warning" class="submit" @click="handleSubmit"
          >提交订单</el-button
        >
        <!-- 临时登录 -->
        <div class="simplelogin">
          <SimpleLogin :showDialog="centerDialogVisible"></SimpleLogin>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { checkIdNumberValid } from "@/static/util";
import SimpleLogin from "@/components/user/SimpleLogin.vue";
export default {
  components: {
    SimpleLogin
  },
  props: ["ticketdata"],
  data() {
    var validatePass = (rule, value, callback) => {
      let val = checkIdNumberValid(value);
      if (val) {
        callback();
      } else if (!value) {
        callback(new Error("请填写身份证号码"));
      } else {
        callback(new Error("身份证输入有误！"));
      }
    };
    return {
      users: [
        {
          username: "",
          id: ""
        }
      ],
      insurances: [], // 保险数据
      ruleForm: {
        contactName: "", // 联系人名字
        contactPhone: "", // 联系人电话
        captcha: "", // 验证码
        invoice: false // 发票
      },
      centerDialogVisible: false,
      //表单校验规则
      rules: {
        username: [
          {
            required: true,
            message: "联系人不能为空",
            trigger: "blur"
          }
        ],
        id: [
          { required: true, message: "请填写身份证号码", trigger: "blur" },
          { required: true, validator: validatePass, trigger: "blur" }
        ],
        contactName: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: "手机号格式不正确！",
            trigger: "blur"
          }
        ],
        captcha: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          { min: 6, message: "验证码格式错误", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    console.log("测试保险数据", this.insurances);
  },
  // 计算总价格
  computed: {
    allPrice() {
      // 计算总价格
      // 应付金额=(成人机票价格+机建/燃油+保险费用)*人头数
      let price = 0;
      let person = this.users.length; //这个是乘坐飞机的人数
      // 1，计算成人机票
      price += this.ticketdata.seat_infos.org_settle_price * person;
      // 2，计算保险的费用
      // this.insurances.forEach(idx => {
      //   price += this.ticketdata.insurances[idx - 1].price * person;
      // });
      this.ticketdata.insurances.forEach(element => {
        if (this.insurances.indexOf(element.id) >= 0) {
          price += element.price * person;
        }
      });
      // 3,计算机建/燃油的费用
      price += this.ticketdata.airport_tax_audlet * person;
      // 触发事件，将总金额传到父组件中
      this.$emit("setAllPrice", price);
      return price;
    }
  },
  methods: {
    changeShow(arg) {
      this.centerDialogVisible = arg;
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        name: "",
        ID: ""
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },
    handleInsurance(id) {
      // 判断数组中是否存在该保险id,如果存在则点击删除它
      if (this.insurances.indexOf(id) > -1) {
        // 存在
        let index = this.insurances.indexOf(id);
        this.insurances.splice(index, 1);
      } else {
        // 不存在则添加到insurances中
        this.insurances.push(id);
      }
      console.log("测试保险数据", this.insurances);
    },
    // 发送手机验证码
    handleSendCaptcha() {
      // 发送验证码之前先判断电话号码的格式是否准确
      //电话号码为空
      if (!this.ruleForm.contactPhone) {
        this.$confirm("手机号码不能为空", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
        return;
      }
      //  电话号码不够11位
      if (this.ruleForm.contactPhone.length !== 11) {
        this.$confirm("手机号码格式错误", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning"
        });
        return;
      }
      // 发送ajax请求
      this.$axios({
        url: "/captchas",
        method: "post",
        data: {
          tel: this.ruleForm.contactPhone
        }
      })
        .then(res => {
          const { code } = res.data;
          if (code) {
            this.$confirm(`模拟手机验证码为：${code}`, "提示", {
              confirmButtonText: "确定",
              showCancelButton: false,
              type: "success"
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 提交订单
    handleSubmit() {
      // 提交之前先判断当前是不是处在登录状态
      if (!this.$store.state.user.userInfo.token) {
        this.centerDialogVisible = true;
      } else {
        const orderInfo = {
          users: this.users,
          insurances: this.insurances,
          contactName: this.ruleForm.contactName,
          contactPhone: this.ruleForm.contactPhone,
          invoice: this.ruleForm.invoice,
          captcha: this.ruleForm.captcha,
          seat_xid: this.$route.query.seat_xid,
          air: this.$route.query.id
        };
        // 测试表单数据
        console.log("表单数据", orderInfo);
        this.$axios({
          url: "/airorders",
          method: "post",
          data: orderInfo,
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token
          }
        }).then(res => {
          console.log("返回的数据", res);
          const { data, message } = res.data;
          if (message == "订单提交成功") {
            this.$message({
              message: message,
              type: "success"
            });
          }
          // 跳转到付款页面
          this.$router.push({
            path: "/air/Pay",
            query: {
              id: data.id
            }
          });
        });
      }
    }
  }
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}
/deep/ .el-form-item__error {
  left: 130px;
}
.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #888;
  width: 20px;
  height: 20px;
  font-size: 16px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
  &:hover {
    background: #66b1ff;
  }
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
</style>
